import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { type RouteRecordRaw } from 'vue-router'
import router from '@/router'
import { useUserStore } from './user'
import type { RouteMenu } from '@/api/system/types'

// 从 localStorage 获取缓存的路由
const ROUTES_KEY = 'cached_routes'
const getCachedRoutes = () => {
    const cached = localStorage.getItem(ROUTES_KEY)
    return cached ? JSON.parse(cached) : []
}

// 添加权限比较函数
function isPermissionsEqual(set1: Set<string | undefined>, set2: Set<string>) {
    // 过滤掉 undefined 值
    const filteredSet1 = new Set([...set1].filter((p): p is string => p !== undefined))

    // 如果大小不同，直接返回 false
    if (filteredSet1.size !== set2.size) return false

    // 检查每个权限是否都存在于另一个集合中
    for (const permission of filteredSet1) {
        if (!set2.has(permission)) return false
    }

    return true
}

export const usePermissionStore = defineStore('permission', () => {
    const dynamicRoutes = ref<RouteRecordRaw[]>(getCachedRoutes())
    const userStore = useUserStore()

    // 获取菜单路由
    const menuRoutes = computed(() => {
        // 获取静态路由中的 dashboard
        const dashboardRoute = router.options.routes
            .find(r => r.path === '/')
            ?.children?.find(r => r.path === 'dashboard')

        // 构建路由树
        const routeTree: RouteRecordRaw[] = []

        // 添加 dashboard
        if (dashboardRoute) {
            routeTree.push({
                ...dashboardRoute,
                path: '/dashboard'
            })
        }

        // 添加动态路由
        routeTree.push(...dynamicRoutes.value)

        // console.log('Menu routes:', routeTree)
        return routeTree
    })

    // 初始化路由
    const initRoutes = async () => {
        console.log('initRoutes')
        const userStore = useUserStore()

        // 只在有token但没有权限信息时重新获取
        if (userStore.token && !userStore.permissions.length) {
            await userStore.getUserInfo()
            await generateRoutes()
        } else if (dynamicRoutes.value.length) {
            // 有缓存路由时，验证权限是否匹配
            const cachedPermissions = new Set(dynamicRoutes.value.map(r => r.meta?.permission).filter(Boolean))
            const currentPermissions = new Set(userStore.permissions)

            // 权限不匹配时重新生成路由
            if (!isPermissionsEqual(cachedPermissions, currentPermissions)) {
                await generateRoutes()
            } else {
                // 权限匹配时直接使用缓存
                dynamicRoutes.value.forEach(route => {
                    if (!router.hasRoute(route.name!)) {
                        router.addRoute(route)
                    }
                })
            }
        }
    }

    // 生成路由
    const generateRoutes = async () => {
        try {
            // 清除现有路由
            clearRoutes()

            const userStore = useUserStore()
            if (!userStore.menus?.length) {
                throw new Error('No menu data available')
            }

            // 生成新路由
            const routes = generateAsyncRoutes(userStore.menus)

            // 添加路由
            routes.forEach(route => router.addRoute(route))

            // 更新store和缓存
            dynamicRoutes.value = routes
            localStorage.setItem(ROUTES_KEY, JSON.stringify(routes))

            // 添加404路由
            if (router.hasRoute('404')) {
                router.removeRoute('404')
            }
            router.addRoute({
                path: '/:pathMatch(.*)*',
                name: '404',
                redirect: '/404'
            })

            return routes
        } catch (error) {
            console.error('Failed to generate routes:', error)
            throw error
        }
    }

    // 清除路由缓存
    const clearRoutes = () => {
        dynamicRoutes.value = []
        localStorage.removeItem(ROUTES_KEY)
    }

    // 预定义组件映射
    const layoutComponent = () => import('@/layouts/Index.vue')
    const views = import.meta.glob('@/views/**/*.vue')
    // 动态生成路由
    function generateAsyncRoutes(menus: RouteMenu[]): RouteRecordRaw[] {
        const routes: RouteRecordRaw[] = []

        menus.forEach(menu => {
            // 只处理目录和菜单
            if (menu.type !== 2) {
                // 处理路径
                let routePath = ''
                if (menu.parentId === 0) {
                    // 根路由，确保只有一个前导斜杠
                    routePath = `/${menu.path.replace(/^\/+/, '')}`
                } else {
                    // 子路由，移除所有斜杠
                    routePath = menu.path.replace(/^\/+/, '').replace(/\/+$/, '')
                }

                // 生成唯一的路由名称
                const routeName = routePath.replace(/\//g, '-').replace(/^-+|-+$/g, '')

                const route: RouteRecordRaw = {
                    path: routePath,
                    name: routeName,
                    meta: {
                        title: menu.title,
                        icon: menu.icon,
                        permission: menu.permission
                    },
                    children: menu.children ? generateAsyncRoutes(menu.children) : []
                }

                // 设置组件
                if (menu.type === 0) {
                    // 如果是目录，使用布局组件
                    route.component = layoutComponent
                    // 如果有子路由，设置重定向到第一个子路由
                    if (route.children && route.children.length > 0) {
                        const firstChild = route.children[0]
                        route.redirect = `${route.path}/${firstChild.path}`
                    }
                } else if (menu.component) {
                    // 如果是菜单且有组件配置，使用动态导入
                    const viewPath = `/src/views/${menu.component}.vue`
                    const component = views[viewPath]
                    if (!component) {
                        console.warn(`Component not found: ${viewPath}`)
                        route.component = views['/src/views/error/404.vue']
                    } else {
                        route.component = component
                    }
                }
                routes.push(route)
            }
        })

        return routes
    }

    return {
        dynamicRoutes,
        menuRoutes,
        generateRoutes,
        initRoutes,
        clearRoutes
    }
}) 